package edu.zut.cs.javaee.manager.config;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import edu.zut.cs.javaee.manager.base.exception.GlobalException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class ApiInterceptor implements HandlerInterceptor {

    @Autowired
    private ServletContext application;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getParameter("userId");
        String token1 = request.getParameter("token");
        String role = request.getParameter("role");
        if (ObjectUtils.isEmpty(userId)) {
            throw new GlobalException(401,"抱歉，请先登陆");
        }
        Object object = application.getAttribute(token1);
        if (ObjectUtils.isEmpty(object)) {
            throw new GlobalException(401,"抱歉，请先登陆");
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
